package com.frank.demo.nio.netty.chat;

import com.frank.demo.nio.netty.http.NamedThreadFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Server {

    public static void main(String[] args) throws InterruptedException {
        new Server().init();
    }

    public void init() throws InterruptedException {
        ServerBootstrap bootstrap = new ServerBootstrap();
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1, new NamedThreadFactory("boss@"));
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(1, new NamedThreadFactory("worker@"));
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
        bootstrap.childHandler(
                new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                          .addLast(
                                new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        System.out.println(((ByteBuf) msg).toString(CharsetUtil.UTF_8));

                                        ctx.write(msg);
                                        ((ByteBuf) msg).clear();
                                    }

                                    @Override
                                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
                                    }

                                    @Override
                                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                        super.exceptionCaught(ctx, cause);
                                    }
                                }
                        );
                    }
                }
        );
        ChannelFuture channelFuture = bootstrap.bind(7777).sync();
        channelFuture.channel().closeFuture().sync();
    }
}
